package com.seal.commons.generator.engine.impl;

import com.seal.commons.generator.engine.TemplateEngine;
import com.seal.commons.generator.util.StringPool;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;

/**
 * 功能描述: <br/>
 *
 * @author yong.huang
 * @date: 2020-09-11 10:50<br/>
 * @since JDK 1.8
 */
public class FreemarkerTemplateEngine implements TemplateEngine {

    public static final Logger LOGGER = LoggerFactory.getLogger(FreemarkerTemplateEngine.class);

    public static final String DEFAULT_ENCODING = "UTF-8";

    private Configuration configuration ;


    public FreemarkerTemplateEngine(){
        this.configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        this.configuration.setDefaultEncoding(DEFAULT_ENCODING);
        this.configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, StringPool.SLASH);
    }

    @Override
    public void engine(Map<String, Object> params, String templatePath, String outFilePath) {
        try {
            Template template = configuration.getTemplate(templatePath);
            if(!createFile(outFilePath)){
                throw new FileNotFoundException();
            }
            try (FileOutputStream fileOutputStream = new FileOutputStream(outFilePath)) {
                template.process(params, new OutputStreamWriter(fileOutputStream, DEFAULT_ENCODING));
            }
            LOGGER.debug("模板:" + templatePath + ";  文件:" + outFilePath);
        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e);
        }
    }


    public boolean createFile(String descFileName) {
        File file = new File(descFileName);
        if (file.exists()) {
            return false;
        }
        if (descFileName.endsWith(File.separator)) {
            return false;
        }
        if (!file.getParentFile().exists()) {
            // 如果文件所在的目录不存在，则创建目录
            if (!file.getParentFile().mkdirs()) {
                return false;
            }
        }

        // 创建文件
        try {
            if (file.createNewFile()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }

    }



}